package com.lifeverse.service;

import com.lifeverse.dto.ConsciousnessStateCreateDTO;
import com.lifeverse.dto.ConsciousnessStateDTO;
import com.lifeverse.dto.ConsciousnessStateUpdateDTO;
import com.lifeverse.entity.ConsciousnessState;
import com.lifeverse.entity.LifeEntity;
import com.lifeverse.event.ConsciousnessStateChangeEvent;
import com.lifeverse.exception.BusinessException;
import com.lifeverse.repository.ConsciousnessStateRepository;
import com.lifeverse.repository.LifeEntityRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 意识状态管理服务
 */
@Slf4j
@Service
@RequiredArgsConstructor
@Transactional(readOnly = true)
public class ConsciousnessService {
    
    private final ConsciousnessStateRepository consciousnessStateRepository;
    private final LifeEntityRepository lifeEntityRepository;
    private final ApplicationEventPublisher eventPublisher;
    
    /**
     * 创建意识状态
     */
    @Transactional
    public ConsciousnessStateDTO createConsciousnessState(ConsciousnessStateCreateDTO createDTO) {
        log.info("创建意识状态，生命体ID: {}, 状态类型: {}", createDTO.getLifeEntityId(), createDTO.getStateType());
        
        // 验证生命体是否存在
        LifeEntity lifeEntity = lifeEntityRepository.findById(createDTO.getLifeEntityId())
                .orElseThrow(() -> new BusinessException("生命体不存在，ID: " + createDTO.getLifeEntityId()));
        
        // 创建意识状态实体
        ConsciousnessState consciousnessState = new ConsciousnessState();
        BeanUtils.copyProperties(createDTO, consciousnessState);
        consciousnessState.setLifeEntity(lifeEntity);
        
        // 设置默认值
        if (consciousnessState.getStateTimestamp() == null) {
            consciousnessState.setStateTimestamp(LocalDateTime.now());
        }
        
        // 计算质量评分
        if (consciousnessState.getQualityScore() == null) {
            consciousnessState.setQualityScore(calculateQualityScore(consciousnessState));
        }
        
        // 检测异常状态
        if (consciousnessState.getIsAnomaly() == null) {
            consciousnessState.setIsAnomaly(detectAnomaly(consciousnessState));
        }
        
        // 保存意识状态
        ConsciousnessState savedState = consciousnessStateRepository.save(consciousnessState);
        
        // 发布状态创建事件
        publishStateChangeEvent(ConsciousnessStateChangeEvent.EventType.STATE_CREATED, savedState, null);
        
        // 检查并发布特殊事件
        checkAndPublishSpecialEvents(savedState);
        
        log.info("意识状态创建成功，ID: {}", savedState.getId());
        return convertToDTO(savedState);
    }
    
    /**
     * 更新意识状态
     */
    @Transactional
    public ConsciousnessStateDTO updateConsciousnessState(Long id, ConsciousnessStateUpdateDTO updateDTO) {
        log.info("更新意识状态，ID: {}", id);
        
        ConsciousnessState existingState = consciousnessStateRepository.findById(id)
                .orElseThrow(() -> new BusinessException("意识状态不存在，ID: " + id));
        
        // 保存更新前的状态
        ConsciousnessState previousState = new ConsciousnessState();
        BeanUtils.copyProperties(existingState, previousState);
        
        // 更新字段
        updateStateFields(existingState, updateDTO);
        
        // 重新计算质量评分
        existingState.setQualityScore(calculateQualityScore(existingState));
        
        // 重新检测异常状态
        if (updateDTO.getIsAnomaly() == null) {
            existingState.setIsAnomaly(detectAnomaly(existingState));
        }
        
        // 保存更新
        ConsciousnessState updatedState = consciousnessStateRepository.save(existingState);
        
        // 发布状态更新事件
        publishStateChangeEvent(ConsciousnessStateChangeEvent.EventType.STATE_UPDATED, updatedState, previousState);
        
        // 检查并发布特殊事件
        checkAndPublishSpecialEvents(updatedState);
        
        log.info("意识状态更新成功，ID: {}", updatedState.getId());
        return convertToDTO(updatedState);
    }
    
    /**
     * 结束意识状态
     */
    @Transactional
    public ConsciousnessStateDTO endConsciousnessState(Long id) {
        log.info("结束意识状态，ID: {}", id);
        
        ConsciousnessState consciousnessState = consciousnessStateRepository.findById(id)
                .orElseThrow(() -> new BusinessException("意识状态不存在，ID: " + id));
        
        if (consciousnessState.getEndTimestamp() != null) {
            throw new BusinessException("意识状态已经结束，ID: " + id);
        }
        
        // 结束状态
        consciousnessState.endState();
        
        // 保存更新
        ConsciousnessState endedState = consciousnessStateRepository.save(consciousnessState);
        
        // 发布状态结束事件
        publishStateChangeEvent(ConsciousnessStateChangeEvent.EventType.STATE_ENDED, endedState, null);
        
        log.info("意识状态结束成功，ID: {}, 持续时间: {} 秒", endedState.getId(), endedState.getDurationSeconds());
        return convertToDTO(endedState);
    }
    
    /**
     * 根据ID查询意识状态
     */
    public ConsciousnessStateDTO getConsciousnessStateById(Long id) {
        log.debug("查询意识状态，ID: {}", id);
        
        ConsciousnessState consciousnessState = consciousnessStateRepository.findById(id)
                .orElseThrow(() -> new BusinessException("意识状态不存在，ID: " + id));
        
        return convertToDTO(consciousnessState);
    }
    
    /**
     * 根据生命体ID查询意识状态列表
     */
    public List<ConsciousnessStateDTO> getConsciousnessStatesByLifeEntity(Long lifeEntityId) {
        log.debug("查询生命体的意识状态列表，生命体ID: {}", lifeEntityId);
        
        List<ConsciousnessState> states = consciousnessStateRepository.findByLifeEntityIdAndDeletedFalse(lifeEntityId);
        return states.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }
    
    /**
     * 根据生命体ID和状态类型查询意识状态列表
     */
    public List<ConsciousnessStateDTO> getConsciousnessStatesByLifeEntityAndType(Long lifeEntityId, ConsciousnessState.StateType stateType) {
        log.debug("查询生命体的特定类型意识状态列表，生命体ID: {}, 状态类型: {}", lifeEntityId, stateType);
        
        List<ConsciousnessState> states = consciousnessStateRepository.findByLifeEntityIdAndStateTypeAndDeletedFalse(lifeEntityId, stateType);
        return states.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }
    
    /**
     * 查询活跃的意识状态
     */
    public List<ConsciousnessStateDTO> getActiveConsciousnessStates() {
        log.debug("查询所有活跃的意识状态");
        
        List<ConsciousnessState> activeStates = consciousnessStateRepository.findActiveStates();
        return activeStates.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }
    
    /**
     * 根据生命体ID查询活跃的意识状态
     */
    public List<ConsciousnessStateDTO> getActiveConsciousnessStatesByLifeEntity(Long lifeEntityId) {
        log.debug("查询生命体的活跃意识状态，生命体ID: {}", lifeEntityId);
        
        List<ConsciousnessState> activeStates = consciousnessStateRepository.findActiveStatesByLifeEntity(lifeEntityId);
        return activeStates.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }
    
    /**
     * 查询异常的意识状态
     */
    public List<ConsciousnessStateDTO> getAnomalousConsciousnessStates() {
        log.debug("查询所有异常的意识状态");
        
        List<ConsciousnessState> anomalousStates = consciousnessStateRepository.findByIsAnomalyTrueAndDeletedFalse();
        return anomalousStates.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }
    
    /**
     * 查询高强度的意识状态
     */
    public Page<ConsciousnessStateDTO> getHighIntensityConsciousnessStates(BigDecimal minIntensity, Pageable pageable) {
        log.debug("查询高强度意识状态，最小强度: {}", minIntensity);
        
        Page<ConsciousnessState> highIntensityStates = consciousnessStateRepository.findHighIntensityStates(minIntensity, pageable);
        List<ConsciousnessStateDTO> dtoList = highIntensityStates.getContent().stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
        
        return new PageImpl<>(dtoList, pageable, highIntensityStates.getTotalElements());
    }
    
    /**
     * 查询最近的意识状态
     */
    public List<ConsciousnessStateDTO> getRecentConsciousnessStates(LocalDateTime since) {
        log.debug("查询最近的意识状态，起始时间: {}", since);
        
        List<ConsciousnessState> recentStates = consciousnessStateRepository.findRecentStates(since);
        return recentStates.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }
    
    /**
     * 查询需要关注的意识状态
     */
    public List<ConsciousnessStateDTO> getConsciousnessStatesNeedingAttention(BigDecimal qualityThreshold) {
        log.debug("查询需要关注的意识状态，质量阈值: {}", qualityThreshold);
        
        List<ConsciousnessState> statesNeedingAttention = consciousnessStateRepository.findStatesNeedingAttention(qualityThreshold);
        return statesNeedingAttention.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }
    
    /**
     * 根据时间段查询意识状态
     */
    public List<ConsciousnessStateDTO> getConsciousnessStatesByTimePeriod(LocalDateTime startTime, LocalDateTime endTime) {
        log.debug("查询时间段内的意识状态，开始时间: {}, 结束时间: {}", startTime, endTime);
        
        List<ConsciousnessState> states = consciousnessStateRepository.findByTimePeriod(startTime, endTime);
        return states.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }
    
    /**
     * 删除意识状态（软删除）
     */
    @Transactional
    public void deleteConsciousnessState(Long id) {
        log.info("删除意识状态，ID: {}", id);
        
        ConsciousnessState consciousnessState = consciousnessStateRepository.findById(id)
                .orElseThrow(() -> new BusinessException("意识状态不存在，ID: " + id));
        
        consciousnessState.setDeleted(true);
        consciousnessStateRepository.save(consciousnessState);
        
        log.info("意识状态删除成功，ID: {}", id);
    }
    
    /**
     * 计算质量评分
     */
    private BigDecimal calculateQualityScore(ConsciousnessState state) {
        // 基于各项指标计算综合质量评分
        BigDecimal overallScore = state.calculateOverallScore();
        
        // 考虑异常状态的影响
        if (Boolean.TRUE.equals(state.getIsAnomaly())) {
            overallScore = overallScore.multiply(BigDecimal.valueOf(0.7)); // 异常状态降低30%评分
        }
        
        // 考虑认知负载的影响
        if (state.getCognitiveLoad().compareTo(BigDecimal.valueOf(80)) > 0) {
            overallScore = overallScore.multiply(BigDecimal.valueOf(0.9)); // 高认知负载降低10%评分
        }
        
        return overallScore.min(BigDecimal.valueOf(100)).max(BigDecimal.ZERO);
    }
    
    /**
     * 检测异常状态
     */
    private Boolean detectAnomaly(ConsciousnessState state) {
        // 强度级别异常
        if (state.getIntensityLevel().compareTo(BigDecimal.valueOf(95)) > 0 || 
            state.getIntensityLevel().compareTo(BigDecimal.valueOf(5)) < 0) {
            return true;
        }
        
        // 认知负载异常
        if (state.getCognitiveLoad().compareTo(BigDecimal.valueOf(90)) > 0) {
            return true;
        }
        
        // 各项指标严重不平衡
        BigDecimal maxValue = state.getCreativityIndex()
                .max(state.getLogicClarity())
                .max(state.getIntuitionSensitivity())
                .max(state.getSocialActivity());
        BigDecimal minValue = state.getCreativityIndex()
                .min(state.getLogicClarity())
                .min(state.getIntuitionSensitivity())
                .min(state.getSocialActivity());
        
        if (maxValue.subtract(minValue).compareTo(BigDecimal.valueOf(70)) > 0) {
            return true;
        }
        
        return false;
    }
    
    /**
     * 更新状态字段
     */
    private void updateStateFields(ConsciousnessState existingState, ConsciousnessStateUpdateDTO updateDTO) {
        if (updateDTO.getStateType() != null) {
            existingState.setStateType(updateDTO.getStateType());
        }
        if (updateDTO.getIntensityLevel() != null) {
            existingState.setIntensityLevel(updateDTO.getIntensityLevel());
        }
        if (updateDTO.getAttentionFocus() != null) {
            existingState.setAttentionFocus(updateDTO.getAttentionFocus());
        }
        if (updateDTO.getEmotionalState() != null) {
            existingState.setEmotionalState(updateDTO.getEmotionalState());
        }
        if (updateDTO.getCognitiveLoad() != null) {
            existingState.setCognitiveLoad(updateDTO.getCognitiveLoad());
        }
        if (updateDTO.getCreativityIndex() != null) {
            existingState.setCreativityIndex(updateDTO.getCreativityIndex());
        }
        if (updateDTO.getLogicClarity() != null) {
            existingState.setLogicClarity(updateDTO.getLogicClarity());
        }
        if (updateDTO.getIntuitionSensitivity() != null) {
            existingState.setIntuitionSensitivity(updateDTO.getIntuitionSensitivity());
        }
        if (updateDTO.getSocialActivity() != null) {
            existingState.setSocialActivity(updateDTO.getSocialActivity());
        }
        if (updateDTO.getLearningEfficiency() != null) {
            existingState.setLearningEfficiency(updateDTO.getLearningEfficiency());
        }
        if (updateDTO.getMemoryActivity() != null) {
            existingState.setMemoryActivity(updateDTO.getMemoryActivity());
        }
        if (updateDTO.getDecisionCapability() != null) {
            existingState.setDecisionCapability(updateDTO.getDecisionCapability());
        }
        if (updateDTO.getTriggerFactor() != null) {
            existingState.setTriggerFactor(updateDTO.getTriggerFactor());
        }
        if (updateDTO.getOutcomeDescription() != null) {
            existingState.setOutcomeDescription(updateDTO.getOutcomeDescription());
        }
        if (updateDTO.getRelatedEntityIds() != null) {
            existingState.setRelatedEntityIds(updateDTO.getRelatedEntityIds());
        }
        if (updateDTO.getStateData() != null) {
            existingState.setStateData(updateDTO.getStateData());
        }
        if (updateDTO.getQualityScore() != null) {
            existingState.setQualityScore(updateDTO.getQualityScore());
        }
        if (updateDTO.getIsAnomaly() != null) {
            existingState.setIsAnomaly(updateDTO.getIsAnomaly());
        }
        if (updateDTO.getEndTimestamp() != null) {
            existingState.setEndTimestamp(updateDTO.getEndTimestamp());
        }
    }
    
    /**
     * 发布状态变化事件
     */
    private void publishStateChangeEvent(ConsciousnessStateChangeEvent.EventType eventType, 
                                       ConsciousnessState currentState, ConsciousnessState previousState) {
        try {
            ConsciousnessStateChangeEvent event = new ConsciousnessStateChangeEvent(
                    this, eventType, currentState, previousState);
            eventPublisher.publishEvent(event);
            log.debug("发布意识状态变化事件: {}", event.getEventSummary());
        } catch (Exception e) {
            log.error("发布意识状态变化事件失败", e);
        }
    }
    
    /**
     * 检查并发布特殊事件
     */
    private void checkAndPublishSpecialEvents(ConsciousnessState state) {
        // 检查异常状态
        if (Boolean.TRUE.equals(state.getIsAnomaly())) {
            publishStateChangeEvent(ConsciousnessStateChangeEvent.EventType.STATE_ANOMALY_DETECTED, state, null);
        }
        
        // 检查高强度状态
        if (state.getIntensityLevel().compareTo(BigDecimal.valueOf(90)) >= 0) {
            publishStateChangeEvent(ConsciousnessStateChangeEvent.EventType.HIGH_INTENSITY_DETECTED, state, null);
        }
        
        // 检查低质量状态
        if (state.getQualityScore().compareTo(BigDecimal.valueOf(30)) <= 0) {
            publishStateChangeEvent(ConsciousnessStateChangeEvent.EventType.LOW_QUALITY_DETECTED, state, null);
        }
        
        // 检查长时间状态
        if (state.isLongDuration()) {
            publishStateChangeEvent(ConsciousnessStateChangeEvent.EventType.LONG_DURATION_DETECTED, state, null);
        }
    }
    
    /**
     * 转换为DTO
     */
    private ConsciousnessStateDTO convertToDTO(ConsciousnessState state) {
        ConsciousnessStateDTO dto = new ConsciousnessStateDTO();
        BeanUtils.copyProperties(state, dto);
        
        // 设置生命体信息
        if (state.getLifeEntity() != null) {
            dto.setLifeEntityId(state.getLifeEntity().getId());
            dto.setLifeEntityName(state.getLifeEntity().getName());
        }
        
        return dto;
    }
}